package com.eastcom.common.db;

public class SessionFactory {

	private ThreadLocal sessions=new ThreadLocal();
	
	protected static String sourceName = "java:comp/env/jdbc/ResourceManager";
	
	private static SessionFactory instance=null;
	
	private SessionFactory(){}
	
	private SessionFactory(String sourceName){
		this.sourceName=sourceName;
	}
	
	public static SessionFactory getInstance(){
		if(instance==null){
    		synchronized(SessionFactory.class){
    			if(instance==null)			
    		        instance=new SessionFactory();

        		SessionFactory.class.notify();
    		}
    		
    	}
    	
    	return instance;
	}
	
	public static SessionFactory getInstance(String sourceName){
		if(instance==null){
    		synchronized(SessionFactory.class){
    			if(instance==null)			
    		        instance=new SessionFactory(sourceName);

        		SessionFactory.class.notify();
    		}
    		
    	}
    	
    	return instance;
	}
	
	public Session getSession() throws Exception{
		Session session=(Session) sessions.get();
		
		if(session==null){
			session=new Session();
			sessions.set(session);
		}
		
		return session;
	}
	
	public void closeSession(Session session){
		if(session!=null)
			session.close();
	}
	
	public void closeSession(){
		Session session=(Session) sessions.get();
		if(session!=null){
			session.close();
		    sessions.remove();
		}
		
	}
	
}
